#coding=utf8
import importlib, glob, sys
from ws_setting import core_logger
from core.container import DefaultContainer
from core import websocket

REQUIRED_ATTRS = ("urls", "filters")
DEFAULT_KEY = "default"
MODULE_NAME = "root"
OPEN_KEY = "onopen"
CLOSE_KEY = "onclose"
MAPPING_KEY = "mapping"
FILTER_KEY = "filters"

REQUIRED_URLS_KEYS = (DEFAULT_KEY, MODULE_NAME)


class Validator:
    def __init__(self):
        pass

    def validate_configure_file(self):
        """
            validate if the config file is correct
        """
        all_configures = glob.glob('*_config.py')
        if not all_configures:
            raise ValueError("no config file")

        if len(all_configures) > 1:
            raise ValueError("can only one config file")

        core_logger.debug("find config file %s" % all_configures[0])
        self.context = all_configures[0].split('_')[0]


    def validate_and_import(self):
        from utils import importUtils
        self.validate_configure_file()

        core_logger.debug("import module named %s" % self.context)
        self.module = importUtils.import_module(self.context + "_config")

        self.validate_configure_content()

        importUtils.import_all_module(self.module)

    def validate_configure_content(self):
        module_dict = self.module.__dict__ 
        def should_contain(specified_dict, keys):
            for necessary_key in keys:
                if not specified_dict.get(necessary_key):
                    raise KeyError("config file must contain key = {}, and can not be null".format(necessary_key))

        should_contain(module_dict, REQUIRED_ATTRS)

        for path, urls_dict in module_dict.get("urls"):
            should_contain(urls_dict, REQUIRED_URLS_KEYS)


